package api

import (
	"api-getway/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"net/http"
)

const endpoint = "117.27.231.169:9000"
const accessKeyID = "ebWNX8Kf32zaiPk3FHDx"
const secretAccessKey = "cHKJkS5Jql5MTliNoJDtSBEpqQqf7j6Pc23cMalX"
const bucketName = "lbb"

func Upload(c *gin.Context) {

	file, _ := c.FormFile("file")
	//打开文件
	open, err := file.Open()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "文件打开失败"})
		return
	}
	//初始化minio客户端
	client, err := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "minio客户端初始化失败"})
		return
	}
	//上传到minio
	objectName := file.Filename
	ContentType := file.Header.Get("Content-Type")
	_, err = client.PutObject(c, bucketName, objectName, open, file.Size, minio.PutObjectOptions{
		ContentType: ContentType,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败"})
		return
	}
	url := fmt.Sprintf("http://%s/%s/%s", endpoint, bucketName, file.Filename)

	c.JSON(http.StatusOK, response.Response{
		Code: 0,
		Msg:  "成功",
		Data: map[string]string{"url": url},
	})

}
